package com.rcp.manager;

/* Restaurant Control Program >> Restaurant Manager */


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.LinkedHashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


@WebServlet("/CreateEmployee")
public class CreateEmployee extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	Connection connection = Nexus.connection;
	Schedule schedule;
	Employee employee;
	
    public CreateEmployee() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//flushTable("employees");
				
		//request.setAttribute("schedule", this.schedule);
		
		//response.sendRedirect("EmployeeCreation.jsp");
		request.getRequestDispatcher("EmployeeCreation.jsp").forward(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//Check if connection is active
		if(this.connection == null){
			establishConnection();
		} else
			try {
				if(this.connection.isClosed()){
					establishConnection();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		
		//Get Schedule
		/*String day = request.getParameter("day");
		
		String inHour = request.getParameter("inHour");
		String inMinute = request.getParameter("inMinute");
		String inAMPM = request.getParameter("inAMPM");

		String outHour = request.getParameter("outHour");
		String outMinute = request.getParameter("outMinute");
		String outAMPM = request.getParameter("outAMPM");*/

		
		boolean firstnameIsValid = request.getParameter("firstname").length() == 0 ? false : true;
		boolean lastnameIsValid  = request.getParameter("lastname").length() == 0 ? false : true;
		boolean passwordIsValid = request.getParameter("password").length() == 0 ? false : true;
		boolean statusIsValid = request.getParameter("status").length() == 0 ? false : true;
		
		String firstname = "";
		String lastname = "";
		String password = "";
		int status = 0;
		
		if( !(firstnameIsValid && lastnameIsValid && passwordIsValid && statusIsValid) ){
			errorPage(response, firstnameIsValid, lastnameIsValid, passwordIsValid, statusIsValid);	
		}
		else{
			
			firstname = request.getParameter("firstname");
			lastname =  request.getParameter("lastname");
			password = request.getParameter("password");
			status = Integer.parseInt(request.getParameter("status"));
		
			//Update Database (New Employee)
			try {
				String preparedQuery = 
						"INSERT INTO Employees(FirstName, LastName, password, status)" +
						"VALUES (?, ?, ?, ?);";
				
				PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
				ps.setString(1, request.getParameter("firstname"));
				ps.setString(2, request.getParameter("lastname"));
				ps.setString(3, request.getParameter("password"));
				ps.setString(4, request.getParameter("status"));
				
				ps.executeUpdate();
				
				//Insert Schedule
				/*preparedQuery = 
						"INSERT INTO Employees(FirstName, LastName, password, status)" +
						"VALUES (?, ?, ?, ?);";*/
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			int employeeID = 0;
			
			//Acquire Employee ID
			try {
				String preparedQuery = "SELECT EmployeeID FROM Employees WHERE FirstName = ? AND LastName = ? " +
						"AND password = ? AND status = ?;";
				
				PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
				ps.setString(1, request.getParameter("firstname"));
				ps.setString(2, request.getParameter("lastname"));
				ps.setString(3, request.getParameter("password"));
				ps.setString(4, request.getParameter("status"));
				
				ResultSet results = ps.executeQuery();
				results.first();								//VERY important
				
				employeeID = results.getInt("EmployeeID");
					
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			//Create Employee Object
			this.employee = new Employee(employeeID, firstname, lastname, password, status);
			this.schedule = new Schedule();
			
			//Fill out schedule
			
			LinkedHashMap<Integer, String> week = (LinkedHashMap<Integer, String>) request.getSession().getAttribute("week");
			
			String[] clock_in_hr = request.getParameterValues("clock_in_hr");
			String[] clock_in_min = request.getParameterValues("clock_in_min");
			String[] in_time = request.getParameterValues("in_time");
			String[] clock_out_hr = request.getParameterValues("clock_out_hr");
			String[] clock_out_min = request.getParameterValues("clock_out_min");
			String[] out_time = request.getParameterValues("out_time");
			
			//Sanity Check All Fields
			for(int i = 0; i < week.size(); i++){
				if( in_time[i].length() == 0 ){
					clock_in_hr[i] = "-";
					clock_in_min[i] = "-";
					in_time[i] = "-";
					clock_out_hr[i] = "-";
					clock_out_min[i] = "-";
					out_time[i] = "-";
				}
			}
			
			//Fill out schedule
			for(int i = 0; i < week.size(); i++){
				String day = week.get(i + 1);
				String in = clock_in_hr[i] + ":" + clock_in_min[i] + " " + in_time[i];
				String out = clock_out_hr[i] + ":" + clock_out_min[i] + " " + out_time[i];
				
				this.schedule.addDay(day, in, out);
				this.schedule.setEmployeeID(employeeID);
				this.schedule.setFirstname(firstname);
				this.schedule.setLastname(lastname);
			}
			
			//Add to employee
			this.employee.setSchedule(this.schedule);

			//Add Schedule to database
			try {
				String preparedQuery = 
						"INSERT INTO Schedule(EmployeeID, Schedule) " +
						"VALUES (?, ?);"; 
				
				PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
				ps.setInt(1, employeeID);
				ps.setObject(2, this.schedule);
				
				ps.executeUpdate();
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			//doGet(request, response);
			response.sendRedirect("EmployeesTable");
		}
	}
	
	private void errorPage(HttpServletResponse response, boolean firstname, boolean lastname, boolean password, boolean status) throws IOException{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

		out.println("<html>");
		
		out.println("<head>");

		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
		
		out.println("<link href=\"resources/CSS/Featured.css\" rel=\"stylesheet\" type=\"text/css\"/>");

		out.println("<title>Error</title>");

		out.println("</head>");

		out.println("<body>");
		
		out.println("<div class='error'>");
		
		if(!firstname){
			out.println("Error on first name field");
			out.println("<br /><br />");
		}
		
		if(!lastname){
			out.println("Error on last name field");
			out.println("<br /><br />");
		}
		
		if(!password){
			out.println("Error on password field");
			out.println("<br /><br />");
		}
		if(!status){
			out.println("Error on position field");
			out.println("<br /><br />");
		}
		
		out.println("<form action='EmployeeCreation.jsp'>");
		
		out.println("<input type='submit' value='Back' />");

		out.println("</form>");
		
		out.println("</div>");
		
		out.println("</body>");
		
		out.println("</html>");

		out.close();
	}
	
	/*private static void flushTable(String table){
		try {
			String preparedQuery = "DELETE FROM ?;";
			
			PreparedStatement ps = (PreparedStatement) Nexus.connection.prepareStatement(preparedQuery);
			ps.setString(1, table);
			
			ps.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}*/
	
	public void establishConnection(){
		
		String dbURL = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
		String dbName = "";
		String username = "cs437group01";
		String password = "VHj#dj!v";
		String driver = "com.mysql.jdbc.Driver";
		 
		/*
		String dbURL = "jdbc:mysql://localhost:3306/";
		String dbName = "rcp";
		String username = "root";
		String password = "sesame";
		String driver = "com.mysql.jdbc.Driver";
		*/
		
		try {
			Class.forName(driver).newInstance();
			Nexus.connection = (Connection) DriverManager.getConnection(dbURL + dbName, username, password);
			this.connection = Nexus.connection;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void destroy(){
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		super.destroy();
	}

}
